package erfgame.core.graphics.renderer.chain;

import java.util.WeakHashMap;



import erfgame.core.Rotation;
import erfgame.core.entity.Entity;
import erfgame.core.graphics.renderer.EntityRendererFactory;
import erfgame.core.world.World;

public class EntityRendererChainFactory {
	private EntityRendererFactory rendererFactory;
	private WeakHashMap<Entity, RendererChain>[] rendererChains;
	private World currentWorld;
	
	@SuppressWarnings("unchecked")
	public EntityRendererChainFactory( EntityRendererFactory rendererFactory ) {
		this.rendererFactory = rendererFactory;
		this.rendererChains = new WeakHashMap[4];
		for( int i=0; i<rendererChains.length; i++ ) {
			rendererChains[i] = new WeakHashMap<Entity, RendererChain>();
		}
	}
	
	public RendererChain getRendererChain( World world, Entity entity, Rotation viewRotation ) {
		if( world != currentWorld ) {
			for( int i=0; i<rendererChains.length; i++ ) {
				this.rendererChains[i].clear();				
			}
			currentWorld = world; 
		}
		RendererChain result = this.rendererChains[viewRotation.ordinal()].get( entity );
		if( result == null ) {
			result = new RendererChain( this.rendererFactory.getRenderer(world, entity, viewRotation));
			this.rendererChains[viewRotation.ordinal()].put( entity, result );
		}
		return result;
	}
}
